 ///
 /// @file    Derived.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-05-02 16:22:46
 ///
 
#include <iostream>
using std::cout;
using std::endl;


class Base{
public:
	Base(int ibase = 0)
	: _ibase(ibase)
	{	cout << "Base(int=0)" << endl;	}
	
	virtual
	void print() const
	{	cout << "Base::_ibase = " << _ibase << endl;	}

private:
	long _ibase;
};

class Derived
: public Base
{
public:
	Derived(int ibase, int derived)
	: Base(ibase) //显式调用基类的构造函数，是可以防止出现错误
	, _iderived(derived)
	{	cout << "Derived()" << endl;	}
	
	void display() const 
	{
		cout << "Derived::_iderived = " << _iderived << endl;
	}

private:
	long _iderived;
};
 
void test0() 
{
	Base base(2);
	Derived d(1, 10);
	d.display();

	Base * pbase = &d;//ok 基类指针指向了派生类对象
	pbase->print();//该操作是合法的，不需要强制转换

	cout << endl;
	//pbase = &base;
	Derived * pderieved = (Derived*)pbase;//ok, 派生类指针指向了基类指针
	pderieved->display();//强制转换之后，是安全的
	cout << endl;

	//动态转换类型
	//如果转换成功，该指针就是有值的;
	//如果转换失败，该指针就是空指针
	Derived * pderived2 = dynamic_cast<Derived*>(pbase);
	if(pderived2) {
		pderived2->display();
	} else {
		cout << "转换失败" << endl;
	}
} 
 
int main(void)
{
	test0();
	return 0;
}















